//
//  LJOauthViewController.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/18.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import SVProgressHUD

class LJOauthViewController: UIViewController, UIWebViewDelegate {
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = LJNetworkTool.shareInstance.aOuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    navigationItem.title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillAll")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func fillAll(){
        let js = "document.getElementById('userId').value='13428283878'; document.getElementById('passwd').value='7073181197';"
        
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - webView 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在努力加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // 移除状态指示器
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取返回的URL字符串
        let urlString = request.URL!.absoluteString
        print(urlString)
        
        if !urlString.hasPrefix(LJNetworkTool.shareInstance.redirect_uri) {
            // 如果不是回调URL加载界面
            return true
        }
        // 获得？后面的内容
        if let query = request.URL?.query {
            let codeString = "code="
            // 判断是否是以code=开头
            if query.hasPrefix(codeString){
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                
                loadAccessToken(code)
                
            }else{
                self.close()
            }
        }else{
            print("query没有值")
        }
        
        return false
    }
    
    func loadAccessToken(code:String){
        // 调用网络工具类方法
        LJNetworkTool.shareInstance.loadAccessToken(code) { (result, error) -> () in
            if error != nil && result == nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                // 延迟关闭控制器
                print(error)
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.close()
                    })
                return
            }
            //没有错误执行下一步操作
            // 字典转模型
            let userAccount = LJUserAccount(dict: result!)
            // 保存数据
            userAccount.saveUserAccount()
            
            print("userAccount:\(userAccount)")
            
            // 切换跟控制器
            (UIApplication.sharedApplication().delegate as! AppDelegate).swtichRootViewController(false)
            
            // 关闭界面
            self.close()
        }
        
    }

    // MARK: - 懒加载
    lazy var webView = UIWebView()

}
